package cn.xdf.docenhance.utils

import android.graphics.Bitmap

object ImageOps {
    fun adjustBrightnessContrast(src: Bitmap, brightness: Float, contrast: Float): Bitmap {
        val w = src.width
        val h = src.height
        val out = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        val cm = android.graphics.ColorMatrix(floatArrayOf(
            contrast, 0f, 0f, 0f, brightness,
            0f, contrast, 0f, 0f, brightness,
            0f, 0f, contrast, 0f, brightness,
            0f, 0f, 0f, 1f, 0f
        ))
        val paint = android.graphics.Paint().apply { colorFilter = android.graphics.ColorMatrixColorFilter(cm) }
        val canvas = android.graphics.Canvas(out)
        canvas.drawBitmap(src, 0f, 0f, paint)
        return out
    }

    fun sharpen(src: Bitmap): Bitmap {
        val kernel = floatArrayOf(
            0f, -1f, 0f,
            -1f, 5f, -1f,
            0f, -1f, 0f
        )
        return convolve3x3(src, kernel)
    }

    fun applyPresetFilter(src: Bitmap, id: Int): Bitmap {
        // 占位：简单的温暖滤镜
        val cm = android.graphics.ColorMatrix(floatArrayOf(
            1.05f, 0f, 0f, 0f, 10f,
            0f, 1.0f, 0f, 0f, 5f,
            0f, 0f, 0.95f, 0f, 0f,
            0f, 0f, 0f, 1f, 0f
        ))
        val paint = android.graphics.Paint().apply { colorFilter = android.graphics.ColorMatrixColorFilter(cm) }
        val out = Bitmap.createBitmap(src.width, src.height, Bitmap.Config.ARGB_8888)
        android.graphics.Canvas(out).drawBitmap(src, 0f, 0f, paint)
        return out
    }

    private fun convolve3x3(src: Bitmap, kernel: FloatArray): Bitmap {
        val w = src.width
        val h = src.height
        val out = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        val paint = android.graphics.Paint()
        val cm = android.graphics.ColorMatrix()
        val bmp = src.copy(Bitmap.Config.ARGB_8888, true)
        // 手写卷积（注意性能，仅用于测试）
        val pixels = IntArray(w * h)
        src.getPixels(pixels, 0, w, 0, 0, w, h)
        val outPx = IntArray(w * h)
        fun clip(v: Int) = v.coerceIn(0, 255)
        for (y in 1 until h - 1) {
            for (x in 1 until w - 1) {
                var r = 0f; var g = 0f; var b = 0f
                var ki = 0
                for (dy in -1..1) for (dx in -1..1) {
                    val c = pixels[(y + dy) * w + (x + dx)]
                    val kr = kernel[ki++]
                    r += ((c shr 16) and 0xFF) * kr
                    g += ((c shr 8) and 0xFF) * kr
                    b += (c and 0xFF) * kr
                }
                val a = (pixels[y * w + x] ushr 24) and 0xFF
                outPx[y * w + x] = (a shl 24) or (clip(r.toInt()) shl 16) or (clip(g.toInt()) shl 8) or clip(b.toInt())
            }
        }
        out.setPixels(outPx, 0, w, 0, 0, w, h)
        return out
    }
}
